<?php
require_once("$srcdir/options.inc.php");

$months = array("01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12");
$days = array("01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31");
$thisyear = date("Y");
$years = array($thisyear - 1, $thisyear, $thisyear + 1, $thisyear + 2);

if ($viewmode) {
    $id = $_REQUEST['id'];
    $result = sqlQuery("SELECT * FROM form_encounter WHERE id = '$id'");
    $encounter = $result['encounter'];
    if ($result['sensitivity'] && !acl_check('sensitivities', $result['sensitivity'])) {
        echo "<body>\n<html>\n";
        echo "<p>" . xl('You are not authorized to see this encounter.') . "</p>\n";
        echo "</body>\n</html>\n";
        exit();
    }
}

// Sort comparison for sensitivities by their order attribute.
function sensitivity_compare($a, $b) {
    return ($a[2] < $b[2]) ? -1 : 1;
}

// get issues
$ires = sqlStatement("SELECT id, type, title, begdate FROM lists WHERE " .
        "pid = $pid AND enddate IS NULL " .
        "ORDER BY type, begdate");
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
    <head>
        <?php html_header_show(); ?>
        <title><?php xl('Patient Encounter', 'e'); ?></title>
		
       <!-- <link rel="stylesheet" type="text/css" href="<?php echo $GLOBALS['webroot'] ?>/interface/themes/style_metal.css">
       <link rel="stylesheet" type="text/css" href="<?php echo $GLOBALS['webroot'] ?>/interface/themes/nightingale.css">-->
        <link rel="stylesheet" type="text/css" href="<?php echo $GLOBALS['webroot'] ?>/interface/themes/jquery.fancybox.css?v=2.1.5" media="screen"/>
        <link rel="stylesheet" type="text/css" href="<?php echo $GLOBALS['webroot'] ?>/interface/themes/jquery-accordion.css" >
        <link rel="stylesheet" href="<?php echo $web_root; ?>/patients/css/nightingale.css" type="text/css"/>
        <link rel="stylesheet" href="<?php echo $web_root; ?>/patients/css/datepicker.css" type="text/css"/>
        <link rel="stylesheet" href="<?php echo $web_root; ?>/library/js/redmond/jquery-ui-1.10.3.custom.min.css" type="text/css"/>
        <link rel="stylesheet" href="<?php echo $web_root; ?>/patients/css/jquery.autocomplete.css" type="text/css"/>
        <!-- Add jQuery library -->

        <script type="text/javascript" src="<?php echo $GLOBALS['webroot'] ?>/library/js/jquery-1.10.0.min.js"></script>
        <!--        <script type="text/javascript" src="<?php echo $GLOBALS['webroot'] ?>/library/js/jquery-1.7.2.min.js"></script>-->
        <!-- Add mousewheel plugin (this is optional) -->
        <script type="text/javascript" src="<?php echo $GLOBALS['webroot'] ?>/library/js/jquery.mousewheel-3.0.6.pack.js"></script>
        <!-- Add fancyBox main JS and CSS files -->
        <script type="text/javascript" src="<?php echo $GLOBALS['webroot'] ?>/library/js/jquery.fancybox.js"></script>

        <script type="text/javascript" src="<?php echo $web_root; ?>/patients/js/jquery.ui.core.js"></script>
        <script type="text/javascript" src="<?php echo $web_root; ?>/patients/js/jquery.ui.widget.js"></script>
        <script type="text/javascript" src="<?php echo $web_root; ?>/patients/js/jquery.ui.datepicker.js"></script>
        <script type="text/javascript" src="<?php echo $web_root; ?>/patients/js/jquery.mask.min.js"></script>
        
        
        <script type="text/javascript" src="<?php echo $GLOBALS['webroot'] ?>/library/js/common.js"></script>
        <script type="text/javascript" src="<?php echo $GLOBALS['webroot'] ?>/library/dialog.js"></script>
        <script type="text/javascript" src="<?php echo $GLOBALS['webroot'] ?>/library/overlib_mini.js"></script>
        <script type="text/javascript" src="<?php echo $GLOBALS['webroot'] ?>/library/textformat.js"></script>
        <!-- pop up calendar -->
        <!--<style type="text/css">@import url(<?php echo $GLOBALS['webroot'] ?>/library/dynarch_calendar.css);</style>
        <script type="text/javascript" src="<?php echo $GLOBALS['webroot'] ?>/library/dynarch_calendar.js"></script>
        <?php include_once("{$GLOBALS['srcdir']}/dynarch_calendar_en.inc.php"); ?>
        <script type="text/javascript" src="<?php echo $GLOBALS['webroot'] ?>/library/dynarch_calendar_setup.js"></script>
        <?php include_once("{$GLOBALS['srcdir']}/ajax/facility_ajax_jav.inc.php"); ?>-->
        <script type="text/javascript" src="<?php echo $web_root; ?>/patients/js/jquery.autocomplete.js"></script>
        <script language="JavaScript">

            var mypcc = '<?php echo $GLOBALS['phone_country_code'] ?>';

            // Process click on issue title.
            function newissue() {
                dlgopen('../../patient_file/summary/add_edit_issue.php', '_blank', 800, 600);
                return false;
            }

            // callback from add_edit_issue.php:
            function refreshIssue(issue, title) {
                var s = document.forms[0]['issues[]'];
                s.options[s.options.length] = new Option(title, issue, true, true);
            }

            $(document).ready(function() {
                $("#form_date").datepicker({
                    showOn: "button",
                    buttonImage: "<?php echo $web_root; ?>/patients/images/calendar-green.gif",
                    dateFormat: 'dd-mm-yy',
                    buttonImageOnly: true,
                    beforeShow: function() {
                        setTimeout(function() {
                            $('.ui-datepicker').css('z-index', 99999999999999);
                        }, 0);
                    }
                });
                $("#form_date").mask("99-99-9999");
                $(".ui-datepicker-trigger").after(" <span>(dd-mm-aaaa)</span> ");


                $("#cancel").click(function() {
                    parent.jQuery.fancybox.close();
                });

                $("#typid").autocomplete("<?php echo $web_root; ?>/interface/procedures_autocomplete.php",
                        {
                            minChars: 3,
                            matchSubset: 1,
                            matchContains: 1,
                            selectFirst: false,
                            cacheLength: 10,
                            autoFill: false,
                            onItemSelect: function(li) {
                                $("#typid").val($("<div>").html(li.selectValue).text());
                            }
                        });

                $("#typid").result(function(event, data, formatted) {
        //            $("#form_patient").val(data[0]);
                    $("#pc_typid").val(data[1]);
                });


                $("#guardar").click(function() {
                    var category = document.forms[0].pc_catid.value;
                    var reason = document.forms[0].reason.value;
					var tipo = document.forms[0].pc_typid.value;
					var cat = document.forms[0].pc_catid.value;
					var causa = document.forms[0].pc_causaid.value;
					
					if (category == '_blank') {
                        alert("<?php echo xl('You must select a visit category'); ?>");
                        return;
                    }else if(reason==''){
						alert("<?php echo "Debe ingresar una breve descripción de la consulta."; ?>");
					}else if(tipo==''){
						alert("<?php echo "Debe seleccionar un Tipo de consulta."; ?>");
					}else if(cat=='_blank'){
						alert("<?php echo "Debe seleccionar una Categoría de la Consulta."; ?>");
					} else if(causa=='_blank'){
						alert("<?php echo "Debe seleccionar una Causa de la consulta."; ?>");
					} else {
                        $.ajax({
                            data: $("#new_encounter").serialize(), // all form fields,
                            url: $("#new_encounter").attr('action'), //'/interface/forms/newpatient/save.php',
                            type: 'post',
                            cache: false,
                            beforeSend: function() {
                                $("#resultado").html("Procesando, espere por favor...");
                            },
                            success: function(response) {
                                //$("#resultado").html(response);
                                parent.$("#column_left").load("../" + response);
                                parent.jQuery.fancybox.close();
                                //parent.$("#info").load( "../patient_file/summary/demographics.php" );
                                //parent.$("#consulta").hide();
                                //parent.$("#consulta_close").show();
                                
                                //parent.$("#info").load( "../patient_file/summary/demographics.php?set_pid=<?php echo $_SESSION['pid'] ?>", function(){alert($("#column_left").html());} );
                                
                                
                                //parent.$("#column_left").load("../patient_file/summary/get_encounters.php");
                            }
                        });
                    }
                });
            });

            function bill_loc() {
                var pid =<?php echo $pid; ?>;
                var dte = document.getElementById('form_date').value;
                var facility = document.forms[0].facility_id.value;
                ajax_bill_loc(pid, dte, facility);
            }

        </script>
    </head>

    <body style="width:690px !important;height:275px !important; overflow:auto; ">
        <!-- Required for the popup date selectors -->
        <div id="overDiv" style="position:absolute; visibility:hidden; z-index:1000;"></div>

        <form action="<?php echo $rootdir ?>/forms/newpatient/save.php" name='new_encounter' id='new_encounter'>

            <div class="borde_normal">
                <?php if ($viewmode) { ?>
                    <input type=hidden name='mode' value='update'>
                    <input type=hidden name='id' value='<?php echo $_GET["id"] ?>'>
                     <span class="historial_paciente"><i style="font-size: 1.4em;" class="icon-stethoscope"></i> <?php xl('Patient Encounter Form', 'e'); ?> </span>
                <?php } else { ?>
                    <input type='hidden' name='mode' value='new'>
                     <span class="historial_paciente"><i style="font-size: 1.4em;" class="icon-stethoscope"></i> <?php xl('New Encounter Form', 'e'); ?> </span>
                <?php } ?>
               
                <a href="" id="guardar" class="css_button" onclick="return false;"><span><i class="icon-ok-sign" style="font-size: 25px;"></i> <?php xl('Save', 'e'); ?></span></a>
                <a href="" id="cancel" class="css_button"><span><i class="icon-remove-sign" style="font-size: 25px;"></i> <?php xl('Cancel', 'e'); ?></span></a>

            </div>

            <div style="width: 100%; display: table-cell;">
                <table width='96%'>

                    <tr>
                        <td width='34%' rowspan='2' align='center' valign='center' class='text'>
                            <table>
                                <tr<?php if ($GLOBALS['athletic_team']) echo " style='visibility:hidden;'"; ?>>
                                    <td style='text-align:right;' class='bold' nowrap><span class='required'>*</span><?php echo "Tipo de consulta:" ?></td>
                                    <td class='text'>
										<textarea rows='1' cols='50'  name='typid' id='typid'></textarea>
                                        <!--<input type='text' name='typid' id='typid'></input>-->
                                    </td>
                                        <input type="hidden" name="pc_typid" id="pc_typid"></input>
                                </tr>
                                
                                <tr<?php if ($GLOBALS['athletic_team']) echo " style='visibility:hidden;'"; ?>>
                                    <td style='text-align:right;' class='bold' nowrap><span class='required'>*</span><?php xl('Visit Category:', 'e'); ?></td>
                                    <td class='text'>
                                        <select name='pc_catid' id='pc_catid'>
                                            <option value='_blank'><?php xl('Select One', 'e'); ?></option>
                                            <?php
                                            $cres = sqlStatement("SELECT pc_catid, pc_catname " .
                                                    "FROM openemr_postcalendar_categories ORDER BY pc_catname");
                                            while ($crow = sqlFetchArray($cres)) {
                                                $catid = $crow['pc_catid'];
                                                if ($catid != 14 && $catid != 15)
                                                    continue;
                                                echo "       <option value='$catid'";
                                                if ($viewmode && $crow['pc_catid'] == $result['pc_catid'])
                                                    echo " selected";
                                                echo ">" . xl_appt_category($crow['pc_catname']) . "</option>\n";
                                            }
                                            ?>
                                        </select>
                                    </td>
                                </tr>
                                
                                 <tr<?php if ($GLOBALS['athletic_team']) echo " style='visibility:hidden;'"; ?>>
                                     <?php
                                     $pres = sqlStatement("SELECT sex FROM patient_data WHERE pid = " . $_SESSION['pid']);
                                            $prow = sqlFetchArray($pres);
                                     ?>
                                    <td style='text-align:right;<?php if( $prow['sex'] == 'Male' ) echo "display:none;"?>' class='bold' nowrap><?php echo "Condici&oacuten Usuaria:" ?></td>
                                    <td class='text' style='<?php if( $prow['sex'] == 'Male' ) echo "display:none;"?>'>
                                        <select name='pc_condid' id='pc_condid'>
                                            <option value='_blank'><?php xl('Select One', 'e'); ?></option>
                                            <?php
                                            
                                                $cres = sqlStatement("SELECT * FROM `list_options` WHERE list_id = 'Condicion_Usuario' order by seq asc");
                                                while ($crow = sqlFetchArray($cres)) {
                                                    echo "       <option value='".$crow['seq']."'";
                                                    if( $crow['seq'] == $result['pc_condid'] ) echo " selected ";
                                                    echo ">" . $crow['title'] . "</option>\n";
                                                }
                                            
                                            ?>
                                        </select>
                                    </td>
									</tr>
									<tr>     
									<td style='text-align:right;' class='bold' nowrap><span class='required'>*</span><?php echo "Causa de la consulta:" ?></td>
                                    <td class='text'>
                                        <select name='pc_causaid' id='pc_causaid'>
                                            <option value='_blank'><?php xl('Select One', 'e'); ?></option>
                                            <?php
                                            
                                                $cres = sqlStatement("SELECT * FROM `list_options` WHERE list_id = 'Causa_de_la_consulta' order by seq asc");
                                                while ($crow = sqlFetchArray($cres)) {
                                                    echo "       <option value='".$crow['seq']."'";
                                                    if( $crow['seq'] == $result['pc_causaid'] ) echo " selected ";
                                                    echo ">" . $crow['title'] . "</option>\n";
                                                }
                                            
                                            ?>
                                        </select>     
                                    </td>
									</tr>
                                
                                <tr>
                                    <td style='text-align:right;' class='bold' nowrap><?php xl('Date of Service:', 'e'); ?></td>
                                    <td class='text' nowrap>
                                        <input type='text' size='10' name='form_date' id='form_date' <?php echo $disabled ?>
                                               value='<?php echo $viewmode ? date('d-m-Y', strtotime(substr($result['date'], 0, 10))) : date('d-m-Y'); ?>'
                                               title='<?php xl('yyyy-mm-dd Date of service', 'e'); ?>' />
                                    </td>
                                </tr>
                            </table>

                        </td>
                    </tr>
                </table>
            </div>
            <div style="float: left;display:none;">
                <h3 style="font-size: 15px;"><span style="color:red;">*</span><?php echo 'Motivo de consulta'; ?>:</h3>
                <?php
                    $query = "SELECT u.speciality, lo.title FROM users u, list_options lo WHERE u.id = " . $_SESSION['authUserID'] . " AND u.speciality = lo.seq AND lo.list_id = 'especialidades' ";
                    $res = sqlStatement($query);
                    $row = sqlFetchArray($res);
                ?>
                <!--textarea name='reason' cols='35' rows='7' wrap='virtual' ><?php echo $viewmode ? htmlspecialchars($result['reason']) : $GLOBALS['default_chief_complaint']; ?></textarea-->
                <textarea name='reason' cols='35' rows='7' wrap='virtual' >Consulta <?php echo $row['title']?></textarea>
            </div>

            <div style="float: right; width: 54%;display:none;">
                <h3 style="font-size: 15px;"><?php xl('Issues (Injuries/Medical/Allergy)', 'e'); ?> 
                    <span> 
                        <a href="../../patient_file/summary/add_edit_issue.php" class="addIcon css_button css_button_left" style="margin-right: 10px;"
                           onclick="top.restoreSession()"><i class="icon-plus-sign" title="Agregar Incidencias"></i></a>
                    </span>
                </h3>
                <select multiple name='issues[]' size='8' style='width:40%' title='<?php xl('Hold down [Ctrl] for multiple selections or to unselect', 'e'); ?>'>
                    <?php
                    while ($irow = sqlFetchArray($ires)) {
                        $list_id = $irow['id'];
                        $tcode = $irow['type'];
                        if ($ISSUE_TYPES[$tcode])
                            $tcode = $ISSUE_TYPES[$tcode][2];
                        echo "    <option value='$list_id'";
                        if ($viewmode) {
                            $perow = sqlQuery("SELECT count(*) AS count FROM issue_encounter WHERE " .
                                    "pid = '$pid' AND encounter = '$encounter' AND list_id = '$list_id'");
                            if ($perow['count'])
                                echo " selected";
                        }
                        else {
                            // For new encounters the invoker may pass an issue ID.
                            if (!empty($_REQUEST['issue']) && $_REQUEST['issue'] == $list_id)
                                echo " selected";
                        }
                        echo ">$tcode: " . $irow['begdate'] . " " .
                        htmlspecialchars(substr($irow['title'], 0, 40)) . "</option>\n";
                    }
                    ?>
                </select>

                <p style="text-align: left; float: right; font-size: 11px; width: 54%; margin-right: 20px;"><i><?php
                        xl('To link this encounter/consult to an existing issue, click the '
                                . 'desired issue above to highlight it and then click [Save]. '
                                . 'Hold down [Ctrl] button to select multiple issues.', 'e');
                        ?></i>
                </p>
            </div>
            <div style="display:none;">
                <table width='100%'>
                    <tr>
                        <td class='bold' nowrap><?php xl('Facility:', 'e'); ?></td>
                        <td class='text'>
                            <select name='facility_id' onChange="bill_loc()">
                                <?php
                                if ($viewmode) {
                                    $def_facility = $result['facility_id'];
                                } else {
                                    $dres = sqlStatement("select facility_id from users where username = '" . $_SESSION['authUser'] . "'");
                                    $drow = sqlFetchArray($dres);
                                    $def_facility = $drow['facility_id'];
                                }
                                $fres = sqlStatement("select * from facility where service_location != 0 order by name");
                                if ($fres) {
                                    $fresult = array();
                                    for ($iter = 0; $frow = sqlFetchArray($fres); $iter++)
                                        $fresult[$iter] = $frow;
                                    foreach ($fresult as $iter) {
                                        ?>
                                        <option value="<?php echo $iter['id']; ?>" <?php if ($def_facility == $iter['id']) echo "selected"; ?>><?php echo $iter['name']; ?></option>
                                        <?php
                                    }
                                }
                                ?>
                            </select>
                        </td>
                    </tr>
                    <tr>
                        <td class='bold' nowrap><?php echo htmlspecialchars(xl('Billing Facility'), ENT_NOQUOTES); ?>:</td>
                        <td class='text'>
                            <div id="ajaxdiv">
                                <?php
                                billing_facility('billing_facility', $result['billing_facility']);
                                ?>
                            </div>
                        </td>
                    </tr>
                    <tr>
                        <?php
                        $sensitivities = acl_get_sensitivities();
                        if ($sensitivities && count($sensitivities)) {
                            usort($sensitivities, "sensitivity_compare");
                            ?>
                            <td class='bold' nowrap><?php xl('Sensitivity:', 'e'); ?></td>
                            <td class='text'>
                                <select name='form_sensitivity'>
                                    <?php
                                    foreach ($sensitivities as $value) {
                                        // Omit sensitivities to which this user does not have access.
                                        if (acl_check('sensitivities', $value[1])) {
                                            echo "       <option value='" . $value[1] . "'";
                                            if ($viewmode && $result['sensitivity'] == $value[1])
                                                echo " selected";
                                            echo ">" . xl($value[3]) . "</option>\n";
                                        }
                                    }
                                    echo "       <option value=''";
                                    if ($viewmode && !$result['sensitivity'])
                                        echo " selected";
                                    echo ">" . xl('None') . "</option>\n";
                                    ?>
                                </select>
                            </td>
                            <?php
                        } else {
                            ?>
                            <td colspan='2'><!-- sensitivities not used --></td>
                            <?php
                        }
                        ?>
                    </tr>

                    <tr<?php if (!$GLOBALS['gbl_visit_referral_source']) echo " style='visibility:hidden;'"; ?>>
                        <td class='bold' nowrap><?php xl('Referral Source', 'e'); ?>:</td>
                        <td class='text'>
                            <?php
                            echo generate_select_list('form_referral_source', 'refsource', $viewmode ? $result['referral_source'] : '', '');
                            ?>
                        </td>
                    </tr>
                    <tr<?php if ($GLOBALS['ippf_specific'] || $GLOBALS['athletic_team']) echo " style='visibility:hidden;'"; ?>>
                        <td class='bold' nowrap><?php xl('Onset/hosp. date:', 'e'); ?></td>
                        <td class='text' nowrap><!-- default is blank so that while generating claim the date is blank. -->
                            <input type='text' size='10' name='form_onset_date' id='form_onset_date'
                                   value='<?php echo $viewmode && $result['onset_date'] != '0000-00-00 00:00:00' ? substr($result['onset_date'], 0, 10) : ''; ?>' 
                                   title='<?php xl('yyyy-mm-dd Date of onset or hospitalization', 'e'); ?>'
                                   onkeyup='datekeyup(this, mypcc)' onblur='dateblur(this, mypcc)' />
                            <img src='../../pic/show_calendar.gif' align='absbottom' width='24' height='22'
                                 id='img_form_onset_date' border='0' alt='[?]' style='cursor:pointer;cursor:hand'
                                 title='<?php xl('Click here to choose a date', 'e'); ?>'>
                        </td>
                    </tr>

                    <tr>
                        <td class='text' colspan='2' style='padding-top:1em'>
                            <?php if ($GLOBALS['athletic_team']) { ?>
                                <p><i>Click [Add Issue] to add a new issue if:<br />
                                        New injury likely to miss &gt; 1 day<br />
                                        New significant illness/medical<br />
                                        New allergy - only if nil exist</i></p>
                            <?php } ?>
                        </td>
                    </tr>     
                </table>
            </div>
        </form>
    </body>
    <script language="javascript">
            /* required for popup calendar */
//            Calendar.setup({inputField: "form_date", ifFormat: "%Y-%m-%d", button: "img_form_date"});
           // Calendar.setup({inputField: "form_onset_date", ifFormat: "%Y-%m-%d", button: "img_form_onset_date"});
<?php
/*if (!$viewmode) {
    $erow = sqlQuery("SELECT count(*) AS count " .
            "FROM form_encounter AS fe, forms AS f WHERE " .
            "fe.pid = '$pid' AND fe.date = '" . date('Y-m-d 00:00:00') . "' AND " .
            "f.formdir = 'newpatient' AND f.form_id = fe.id AND f.deleted = 0");
    if ($erow['count'] > 0) {
        echo "alert('" . xl('Warning: A visit was already created for this patient today!') . "');\n";
    }
}
?>*/
    </script>

</html>